package com.flesler.actoras.core
{
	import flash.events.EventDispatcher;
	
	public class SimpleActor extends EventDispatcher implements Actor
	{
		private var _name:String;
		private var lastSender:String;
		
		public function SimpleActor(name:String)
		{
			_name = name;
			
			init();
		}
		
		// Private Helpers
		
		private function init():void
		{
			addEventListener(ActorEvent.MESSAGE_RECEIVED, onMessageReceived, false, int.MAX_VALUE);
		}
		
		private function onMessageReceived(e:ActorEvent):void
		{
			lastSender = e.actorName;
			receive.apply(this, e.args);
		}
		
		private function sendArgs(receiver:String, args:Array):void
		{
			dispatchEvent(new ActorEvent(ActorEvent.MESSAGE_SENT, args, receiver));
		}
	
		// Actor Implementation
		
		public function get name():String
		{
			return _name;
		}
		
		public function reply(...args):void
		{
			sendArgs(lastSender, args);
		}
		
		public function send(receiver:String, ...args):void
		{
			sendArgs(receiver, args);
		}
		
		// Exposed Helpers
		
		protected function get sender():String
		{
			return lastSender;
		}
		
		protected function register(actor:Actor):void 
		{
			dispatchEvent(new ActorEvent(ActorEvent.ADDED, actor));
		}
		
		protected virtual function receive(...args):void
		{
		}
	}
}